import 'dart:io';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'l10n/app_localizations.dart';

/// 视频播放页面
/// 用于查看录制的视频
class VideoPlayerPage extends StatefulWidget {
  final String videoPath;

  const VideoPlayerPage({Key? key, required this.videoPath}) : super(key: key);

  @override
  State<VideoPlayerPage> createState() => _VideoPlayerPageState();
}

class _VideoPlayerPageState extends State<VideoPlayerPage> {
  late VideoPlayerController _controller;
  bool _isInitialized = false;
  bool _isPlaying = false;
  double _currentPosition = 0.0;
  double _videoDuration = 0.0;
  String _positionText = '00:00';
  String _durationText = '00:00';

  @override
  void initState() {
    super.initState();
    _initializePlayer();
  }

  /// 初始化视频播放器
  Future<void> _initializePlayer() async {
    // 检查文件是否存在
    final file = File(widget.videoPath);
    if (!await file.exists()) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('视频文件不存在或已被移除')),
        );
      }
      return;
    }

    // 创建播放控制器
    _controller = VideoPlayerController.file(file);

    try {
      // 初始化并设置循环播放
      await _controller.initialize();
      _controller.setLooping(true);

      // 添加位置监听器
      _controller.addListener(_updatePosition);

      if (mounted) {
        setState(() {
          _isInitialized = true;
          _videoDuration = _controller.value.duration.inMilliseconds.toDouble();
          _durationText = _formatDuration(_controller.value.duration);
        });

        // 自动开始播放
        _controller.play();
        setState(() {
          _isPlaying = true;
        });
      }
    } catch (e) {
      print('视频播放器初始化错误: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('无法播放视频: $e')),
        );
      }
    }
  }

  /// 更新播放位置
  void _updatePosition() {
    if (!mounted || !_controller.value.isInitialized) return;

    setState(() {
      _currentPosition = _controller.value.position.inMilliseconds.toDouble();
      _positionText = _formatDuration(_controller.value.position);
      _isPlaying = _controller.value.isPlaying;
    });
  }

  /// 格式化时长为 MM:SS 格式
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return "$minutes:$seconds";
  }

  /// 切换播放/暂停
  void _togglePlay() {
    if (_controller.value.isPlaying) {
      _controller.pause();
    } else {
      _controller.play();
    }
    setState(() {
      _isPlaying = !_isPlaying;
    });
  }

  /// 分享视频
  void _shareVideo() {
    // 此处可以添加分享功能
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('分享功能即将推出')),
    );
  }

  @override
  void dispose() {
    _controller.removeListener(_updatePosition);
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);

    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        foregroundColor: Colors.white,
        title: Text(localizations.recordVideo),
        actions: [
          IconButton(
            icon: const Icon(Icons.share),
            onPressed: _shareVideo,
          ),
        ],
      ),
      body: _isInitialized
          ? Column(
              children: [
                // 视频播放区
                Expanded(
                  child: Center(
                    child: AspectRatio(
                      aspectRatio: _controller.value.aspectRatio,
                      child: VideoPlayer(_controller),
                    ),
                  ),
                ),

                // 播放控制区
                Container(
                  padding: const EdgeInsets.all(16),
                  color: Colors.black,
                  child: Column(
                    children: [
                      // 进度条
                      Row(
                        children: [
                          Text(
                            _positionText,
                            style: const TextStyle(color: Colors.white),
                          ),
                          Expanded(
                            child: Slider(
                              value: _currentPosition,
                              min: 0.0,
                              max: _videoDuration,
                              onChanged: (value) {
                                setState(() {
                                  _currentPosition = value;
                                });
                                _controller.seekTo(
                                    Duration(milliseconds: value.toInt()));
                              },
                            ),
                          ),
                          Text(
                            _durationText,
                            style: const TextStyle(color: Colors.white),
                          ),
                        ],
                      ),

                      // 控制按钮
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          IconButton(
                            icon: Icon(
                              _isPlaying ? Icons.pause : Icons.play_arrow,
                              color: Colors.white,
                              size: 40,
                            ),
                            onPressed: _togglePlay,
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            )
          : const Center(
              child: CircularProgressIndicator(),
            ),
    );
  }
}
